package com.ohuang.jiaxiaotong.View;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.ohuang.jiaxiaotong.R;
public class PsdEditView extends androidx.appcompat.widget.AppCompatEditText {
    private Drawable imgPsd;
    private Drawable imgIcon;
    private Context mContext;
    private Boolean isShow = false;

    public PsdEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    private void init() {
        imgPsd = mContext.getResources().getDrawable(R.mipmap.icon_showpsd);
        imgIcon = mContext.getResources().getDrawable(R.mipmap.icon_psd);
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                setDrawable();
            }
        });
    }


    //绘制图片
    private void setDrawable() {
        if (length() < 1)
            setCompoundDrawablesWithIntrinsicBounds(imgIcon, null, null, null);
        else
            setCompoundDrawablesWithIntrinsicBounds(imgIcon, null, imgPsd, null);
    }

    //当触摸范围在右侧时，触发删除方法，隐藏叉叉
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (imgPsd != null && event.getAction() == MotionEvent.ACTION_UP) {
            int eventX = (int) event.getRawX();
            int eventY = (int) event.getRawY();
            Rect rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - 100;
            if (rect.contains(eventX, eventY)) {
                if (isShow) {
                    setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    imgPsd = mContext.getResources().getDrawable(R.mipmap.icon_hidepsd);
                    setCompoundDrawablesWithIntrinsicBounds(imgIcon, null, imgPsd, null);
                    isShow = false;
                } else {
                    setTransformationMethod(PasswordTransformationMethod.getInstance());
                    imgPsd = mContext.getResources().getDrawable(R.mipmap.icon_showpsd);
                    setCompoundDrawablesWithIntrinsicBounds(imgIcon, null, imgPsd, null);
                    isShow = true;
                }

            }
        }
        return super.onTouchEvent(event);
    }


    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }
}
